package com.limingfeiyu.platform.management.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.limingfeiyu.common.utils.RedisCache;
import com.limingfeiyu.common.web.ResultBody;
import com.limingfeiyu.platform.management.entity.LoginUser;
import com.limingfeiyu.platform.management.entity.NewLoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author :   LiMingFeiYu
 * @Date :   2024-03-10 19:41
 * @Explain: IndexController
 */
@RestController
@Api(value = "首页Controller", tags = {"首页"})
public class IndexController {

    public static String USER_NAME_TOKEN = "USER:NAME:TOKEN:";

    @Autowired
    private RedisCache redisCache;


    @PostMapping("/user/login")
    @ApiOperation(value = "登录", notes = "ResultBody")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名",
                    required = true),
            @ApiImplicitParam(name = "password", value = "密码",
                    required = true)

    })
    public ResultBody<LoginUser> login(@RequestBody LoginUser user, HttpServletRequest request) {
        LoginUser loginUserByUserName = NewLoginUser.getLoginUserByUserName(user.getUserName().trim());
        if (loginUserByUserName == null ||
                !loginUserByUserName.getPassword()
                        .equals(user.getPassword().trim())) {
            return ResultBody.alert().msg("用户或密码错误！");
        }
//        request.getSession().setAttribute(USER_NAME_TOKEN, loginUserByUserName);

        redisCache.set(USER_NAME_TOKEN, loginUserByUserName);
        return ResultBody.ok().data(loginUserByUserName);
    }

    @GetMapping("/user/info")
    @ApiOperation(value = "获取用户信息", notes = "ResultBody")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户名",
                    required = true)
    })
    public ResultBody<LoginUser> getInfo(HttpServletRequest request) {
//        LoginUser attribute = (LoginUser) request.getSession().getAttribute(USER_NAME_TOKEN);
        System.out.println(redisCache.get(USER_NAME_TOKEN));
        LoginUser loginUser = (LoginUser) redisCache.get(USER_NAME_TOKEN);
        return ResultBody.ok().data(loginUser);
    }


    @PostMapping("/user/logout")
    @ApiOperation(value = "退出", notes = "ResultBody")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户名",
                    required = true),


    })
    public ResultBody<LoginUser> logout(@RequestParam("token") String token, HttpServletRequest request) {
        request.getSession().removeAttribute(token);
        return ResultBody.ok();
    }

}
